/* $Id: ProblemUserScoreModel.java 137 2011-08-29 20:33:36Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.models.scores;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Order;

import alt.djudge.frontend.server.Deployment;
import alt.djudge.frontend.server.datatypes.ContestProblemEntry;
import alt.djudge.frontend.server.datatypes.scores.ProblemUserScoreEntry;
import alt.djudge.frontend.server.models.AbstractBigtableModelCore;
import alt.djudge.frontend.server.models.AbstractDBModelCore;
import alt.djudge.frontend.server.models.ContestProblemsModel;
import alt.djudge.frontend.server.models.CoreInterface;


public class ProblemUserScoreModel
{
	private static CoreInterface<ProblemUserScoreEntry> core = Deployment.isGAE() ?  
		new AbstractBigtableModelCore<ProblemUserScoreEntry>()
		{
			@Override
			protected Order getOrdering()
			{
				return Order.asc("id");
			}
			
			@Override
			protected Class<ProblemUserScoreEntry> getEntryClass()
			{
				return ProblemUserScoreEntry.class;
			}
		}
	:
		new AbstractDBModelCore<ProblemUserScoreEntry>()
		{
			@Override
			protected Order getOrdering()
			{
				return Order.asc("id");
			}
			
			@Override
			protected Class<ProblemUserScoreEntry> getEntryClass()
			{
				return ProblemUserScoreEntry.class;
			}
		};		

	// FIXME:
	// clear on
	// OK: submission -> contest, user
	// OK: contestproblem -> contest
	public static HashMap<Long, ProblemUserScoreEntry> getProblemUserEntries(Long contestId, Long userId)
	{
		HashMap<Long, ProblemUserScoreEntry> map = new HashMap<Long, ProblemUserScoreEntry>();
		List<ContestProblemEntry> problemEntries = ContestProblemsModel.getContestEntries(contestId);
		for (ContestProblemEntry problemEntry : problemEntries)
		{
			ProblemUserScoreEntry entry = getProblemUserEntry(problemEntry.getId(), userId);
			map.put(problemEntry.getId(), entry);
		}
		return map;
	}
		
	public static ProblemUserScoreEntry getProblemUserEntry(Long contestProblemId, Long userId)
	{
		ProblemUserScoreEntry entry = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("contestProblemId", contestProblemId);
		List<ProblemUserScoreEntry> list = (List<ProblemUserScoreEntry>) core.getEntries(map);
		if (list.size() > 0)
		{
			entry = list.get(0);
		}
		return entry;
	}

	public static void deleteAllEntries()
	{
		core.deleteAllEntries();
	}
	
	public static List<ProblemUserScoreEntry> getAllEntries()
	{
		List<ProblemUserScoreEntry> list = (List<ProblemUserScoreEntry>) core.getAllEntries();
		return list;
	}	
}
